package com.pingan.mobilegw.adapterservice;

import com.alibaba.fastjson.JSONException;
import com.caucho.hessian.client.HessianProxyFactory;
import com.pingan.mobilegw.mobileservice.invoke.MobileRpcHolder;
import com.pingan.mobilegw.mobileservice.invoke.ServiceInvoker;
import com.pingan.mobilegw.mobileservice.invoke.exception.MethodNotFoundException;
import com.pingan.mobilegw.mobileservice.invoke.exception.ParamMissingException;
import com.pingan.mobilegw.mobileservice.invoke.exception.RpcException;
import com.pingan.mobilegw.mobileservice.invoke.exception.ServiceNotFoundException;
import com.toa.mobile.gw.demo.biz.service.UserInfo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.util.List;

/**
 * 无线RPC调用的Adapter服务
 * 
 * @author jiadao
 * @version $Id: MobileAdapterServiceImpl.java, v 0.1 2013-4-12 下午3:34:58 jiadao Exp $
 */
@Service("mobileAdapterService")
public class MobileAdapterServiceImpl implements MobileAdapterService {

    /** logger */
    private final static Log logger    = LogFactory.getLog(MobileAdapterServiceImpl.class);


    /** 服务调用器 */
    private ServiceInvoker serviceInvoker;

    /**
     * 
     * @see com.pingan.mobilegw.adapterservice.MobileAdapterService#listServices()
     */
    @Override
    public List<MobileServiceInfo> listServices() {
        return this.serviceInvoker.listServices();
    }

    /**
     * 
     * @see com.pingan.mobilegw.adapterservice.MobileAdapterService#mobileService(String, com.pingan.mobilegw.adapterservice.MobileContext, String)
     */
    @Override
    public TargetResponseObject mobileService(String uniqueId, MobileContext context,
                                              String requestData) {
        if(1==1){
            String url =
                    "http://172.17.6.11:8090/userinfo/getUserInfo";
            HessianProxyFactory factory = new HessianProxyFactory();
            UserInfo api = null;
            Class clazz=null;
            try {
                 clazz=Class.forName("com.toa.mobile.gw.demo.biz.service.UserInfo");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

            try {
                api = (UserInfo) factory.create(clazz, url);
                Method m =clazz.getDeclaredMethod("getUserInfo",String.class);
                Object o =m.invoke(api,new String[]{"1111"});
                System.out.println(o);

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }


        }
        if (logger.isInfoEnabled()) {
            logger.info("【" + uniqueId + "】接收到请求:" + requestData + ",conext=" + context);
        }
        long start = System.currentTimeMillis();
        TargetResponseObject response = null;
        ResultEnum errorCode = null;
        try {
            response = this.serviceInvoker.invokeService(uniqueId, context, requestData);
        } catch (IllegalArgumentException e) {
            logger.error(uniqueId + "调用目标方法时参数不合法", e);
            errorCode = ResultEnum.IllegalArgument;
        } catch (ServiceNotFoundException e) {
            logger.error(uniqueId + " 目标服务不存在", e);
            errorCode = ResultEnum.ServiceNotFound;
        } catch (MethodNotFoundException e) {
            logger.error(uniqueId + " 目标方法不存在", e);
            errorCode = ResultEnum.MethodNotFound;
        } catch (ParamMissingException e) {
            logger.error(uniqueId + " 缺少参数", e);
            errorCode = ResultEnum.ParamMissing;
        } catch (JSONException e) {
            logger.error(uniqueId + " JSON解析异常", e);
            errorCode = ResultEnum.JsonParserException;
        } catch (IllegalAccessException e) {
            logger.error(uniqueId + " 调用目标方法权限不合法", e);
            errorCode = ResultEnum.IllegalAccess;
        } catch (InvocationTargetException e) {
            //这个是业务提供的方法抛出了异常
            Throwable bizException = e.getCause();
            if (bizException instanceof RpcException) {
                errorCode = ((RpcException) bizException).getResultCode();
                logger.warn(uniqueId + "rpc异常，resultCode＝" + errorCode.getCode());
            } else {
                errorCode = ResultEnum.BizException;
                logger.error(uniqueId + " 远程业务方法调用抛出异常", e);
            }
        } catch (Throwable e) {
            logger.error(uniqueId + " 未知异常", e);
            errorCode = ResultEnum.UnknowError;
        } finally {
            MobileRpcHolder.clear();
        }

        if (null != errorCode) {
            //发生异常
            response = new TargetResponseObject();
            response.setResult(null);
            response.setUniqueId(uniqueId);
            response.setResultStatus(errorCode.getCode());
        }

        if (logger.isInfoEnabled()) {
            logger.info("【" + uniqueId + "】响应结果:" + response);
        }


        return response;
    }



    public void setServiceInvoker(ServiceInvoker serviceInvoker) {
        this.serviceInvoker = serviceInvoker;
    }

}
